import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:smart_lam/dict/dict.dart';
import 'package:smart_lam/util/dialog.dart';

class HomeController extends GetxController {
  late AnimationController controller;
  late Animation<Offset> animation;
  late AnimationController scaleController;
  late Animation<double> scaleAnimation;

  late FlutterReactiveBle ble;

  @override
  void onInit() {
    controller = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: NavigatorState(),
    );
    scaleController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: NavigatorState(),
    );
    final curve =
        CurvedAnimation(parent: controller, curve: Curves.easeInOutExpo);
    animation = Tween<Offset>(
            begin: Offset(
                ScreenUtil().setWidth(1100), -ScreenUtil().setWidth(100)),
            end: Offset(0.0, 0.0))
        .animate(curve);
    scaleAnimation = Tween<double>(begin: 0.6, end: 1).animate(curve);
    controller.forward();
    scaleController.forward();

    ble = FlutterReactiveBle();
    ble.statusStream.listen((status) async {
      print(status);
      // 仅限Android,位置服务已禁用
      var str = Dict.getByNameKey(bleStatusMap, status);
      late String? confirmText;
      if (str == null || str.isEmpty) {
        return;
      }
      if (Get.context == null) {
        return;
      }
      if (Platform.isAndroid && status == BleStatus.locationServicesDisabled) {
        confirmText = '去设置';
      } else if (status == BleStatus.poweredOff) {
        confirmText = '去开启';
        await CustomDialog.showDialog(
          ctx: Get.context!,
          info: str,
          onConfirm: () {
            Navigator.of(Get.context!).pop(true);
          },
          confirmText: confirmText,
          cancelText: '',
        );
      } else if (status == BleStatus.unsupported) {
        confirmText = '我知道了~';
      } else if (status == BleStatus.unauthorized) {
        confirmText = '去设置';
        await CustomDialog.showDialog(
          ctx: Get.context!,
          info: str,
          onConfirm: () {
            Navigator.of(Get.context!).pop(true);
          },
          confirmText: confirmText,
          cancelText: '',
        );

        await openAppSettings();
      }
    });

    super.onInit();
  }

  @override
  void onReady() async {
    super.onReady();
  }
}
